<template>
  <div class="container">
    <div class="main">
      <div class="header">试题录入</div>
      <div class="form">
        <el-form ref="form" :model="form" :rules="rules" label-width="120px">
          <el-form-item label="学科：" prop="subjectID">
            <el-select
              v-model="form.subjectID"
              placeholder="请选择"
              @change="seachTags(form.subjectID)"
            >
              <el-option
                :label="item.label"
                :value="item.value"
                v-for="item in subjects"
                :key="item.value"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="目录：" prop="catalogID">
            <el-select v-model="form.catalogID" placeholder="请选择">
              <el-option
                :label="item.label"
                :value="item.value"
                v-for="item in directorys"
                :key="item.value"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="企业：" prop="enterpriseID">
            <el-select v-model="form.enterpriseID" placeholder="请选择">
              <el-option
                :label="item.company"
                :value="item.id"
                v-for="item in companys"
                :key="item.id"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="城市：" prop="city">
            <div class="area">
              <el-select
                v-model="form.province"
                placeholder="请选择"
                @change="seachCitys(form.province)"
              >
                <el-option
                  :value="item"
                  v-for="item in provinces"
                  :key="item"
                ></el-option>
              </el-select>
              <el-select v-model="form.city" placeholder="请选择">
                <el-option
                  :value="item"
                  v-for="item in citys"
                  :key="item"
                ></el-option>
              </el-select>
            </div>
          </el-form-item>
          <el-form-item label="方向：" prop="direction">
            <el-select v-model="form.direction" placeholder="请选择">
              <el-option
                :value="item"
                v-for="item in directions"
                :key="item"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="题型：" prop="questionType">
            <el-radio-group
              v-model="form.questionType"
              @change="changeQuestionType"
            >
              <el-radio
                :label="item.value"
                v-for="item in questionTypes"
                :key="item.value"
                >{{ item.label }}</el-radio
              >
            </el-radio-group>
          </el-form-item>
          <el-form-item label="难度：" prop="difficulty">
            <el-radio-group v-model="form.difficulty">
              <el-radio
                :label="item.value"
                v-for="item in difficulties"
                :key="item.value"
                >{{ item.label }}</el-radio
              >
            </el-radio-group>
          </el-form-item>
          <el-form-item label="题干：" prop="question">
            <quill-editor :value.sync="form.question"></quill-editor>
          </el-form-item>
          <el-form-item label="选项：" v-if="!(form.questionType == 3)">
            <div class="radio" v-if="form.questionType == 1">
              <el-radio-group v-model="radioChecked" @change="changeRadio">
                <el-radio
                  v-for="(item, index) in form.options"
                  :key="item.code"
                  :label="item.code"
                >
                  <div class="form-inner">
                    {{ item.code }} <span>：</span>
                    <el-input v-model="item.title"></el-input>
                    <img :src="item.img" alt="" v-if="item.img" />
                    <div class="upload" v-else>
                      <el-upload
                        ref="uploadPic"
                        action=""
                        accept="image/*"
                        :show-file-list="false"
                        :http-request="(file) => uploadPic(file, index)"
                      >
                        <span>上传图片</span>
                      </el-upload>
                      <i
                        class="el-icon-circle-close"
                        @click="delPic(index)"
                        ref="delPic"
                      ></i>
                    </div>
                  </div>
                </el-radio>
              </el-radio-group>
            </div>
            <div class="checkbox" v-if="form.questionType == 2">
              <el-checkbox-group v-model="checkedList" @change="changeCheckbox">
                <el-checkbox
                  v-for="(item, index) in form.options"
                  :key="item.code"
                  :label="item.code"
                >
                  <div class="form-inner">
                    {{ item.code }} <span>：</span>
                    <el-input v-model="item.title"></el-input>
                    <img :src="item.img" alt="" v-if="item.img" />
                    <div class="upload" v-else>
                      <el-upload
                        ref="uploadPic"
                        action=""
                        accept="image/*"
                        :show-file-list="false"
                        :http-request="(file) => uploadPic(file, index)"
                      >
                        <span>上传图片</span>
                      </el-upload>
                      <i
                        class="el-icon-circle-close"
                        @click="delPic(index)"
                        ref="delPic"
                      ></i>
                    </div>
                  </div>
                </el-checkbox>
              </el-checkbox-group>
            </div>
            <el-button
              type="danger"
              @click="addOptions"
              :disabled="form.questionType == 1"
              >+增加选项与答案</el-button
            >
          </el-form-item>
          <el-form-item label="解析视频" prop="videoURL">
            <el-input v-model="form.videoURL"></el-input>
          </el-form-item>
          <el-form-item label="答案解析：" prop="answer">
            <quill-editor :value.sync="form.answer" ref="editor"></quill-editor>
          </el-form-item>
          <el-form-item label="题目备注：" prop="remarks">
            <el-input v-model="form.remarks" type="textarea"></el-input>
          </el-form-item>
          <el-form-item prop="tags" label="试题标签：">
            <el-select v-model="chooseTags" multiple placeholder="请选择">
              <el-option
                :value="item.label"
                v-for="item in tags"
                :key="item.value"
              ></el-option>
            </el-select>
          </el-form-item>

          <el-form-item>
            <el-button
              type="primary"
              @click="submitForm('form')"
              :loading="loading"
              >确认提交</el-button
            >
          </el-form-item>
        </el-form>
      </div>
    </div>
  </div>
</template>

<script>
import { simple as subjectSimple } from '@/api/hmmm/subjects.js'
import { simple as tagsSimple } from '@/api/hmmm/tags.js'
import { simple as directorysSimple } from '@/api/hmmm/directorys.js'
import { list as companesList } from '@/api/hmmm/companys.js'
import { provinces, citys } from '@/api/hmmm/citys.js'
import { difficulty, questionType, direction } from '@/api/hmmm/constants.js'
import {
  add as addQuestion,
  detail as detailQuestion,
  update as updateQuestion
} from '@/api/hmmm/questions.js'
import quillEditor from '../components/ql-editor.vue'
// sdk software development kit 软件开发工具集
import COS from 'cos-js-sdk-v5' // 完成cos对象的初始化

const cos = new COS({
  SecretId: 'AKIDQhmdFckeJk4KUTGqCLPRHsStYjjW7Ufc',
  SecretKey: 'lGZfblojU6XZUItHUWM0UmsmU0KSN6dx'
})
export default {
  name: 'questionsNew',
  components: {
    quillEditor
  },
  data () {
    return {
      form: {
        subjectID: null,
        catalogID: null,
        enterpriseID: null,
        province: null,
        city: null,
        direction: null,
        questionType: 1,
        difficulty: 1,
        question: '',
        options: [
          { isRight: 0, code: 'A', title: '', img: '' },
          { isRight: 0, code: 'B', title: '', img: '' },
          { isRight: 0, code: 'C', title: '', img: '' },
          { isRight: 0, code: 'D', title: '', img: '' }
        ],
        videoURL: '',
        answer: '',
        remarks: null,
        tags: this.tagsSting
      },
      rules: {
        subjectID: [
          { required: true, message: '请选择学科', trigger: 'change' }
        ],
        catalogID: [
          { required: true, message: '请选择目录', trigger: 'change' }
        ],
        enterpriseID: [
          { required: true, message: '请选择企业', trigger: 'change' }
        ],
        direction: [
          { required: true, message: '请选择方向', trigger: 'change' }
        ],
        province: [
          { required: true, message: '请选择省份', trigger: 'change' }
        ],
        city: [{ required: true, message: '请选择城市', trigger: 'change' }],
        questionType: [
          { required: true, message: '请选择题型', trigger: 'change' }
        ],
        difficulty: [
          { required: true, message: '请选择难度', trigger: 'change' }
        ],
        question: [{ required: true, message: '请输入题干', trigger: 'blur' }],
        answer: [
          { required: true, message: '请输入答案解析', trigger: 'blur' }
        ]
      },
      subjects: [],
      tags: [],
      directorys: [],
      companys: [],
      citys,
      difficulties: difficulty,
      questionTypes: questionType,
      directions: direction,
      radioChecked: null,
      checkedList: [],
      chooseTags: [],
      loading: false
    }
  },
  async created () {
    await this.getStartData()
    // 如果有ID则获取渲染初始数据
    if (this.$route.query.id) {
      const res = await detailQuestion({ id: this.$route.query.id })
      const data = res.data
      await this.seachTags(data.subjectID)
      data.questionType = parseInt(data.questionType)
      data.difficulty = parseInt(data.difficulty)
      if (data.questionType === 1) {
        this.radioChecked = data.options.filter((item) => {
          return item.isRight
        })[0]?.code
      } else if (data.questionType === 2) {
        this.checkedList = data.options
          .filter((item) => {
            return item.isRight
          })
          .map((item) => {
            return item.code
          })
      }
      this.chooseTags = data.tags?.split(',')
      this.form = data
      // 去除富文本框自动聚焦
      this.$nextTick(() => {
        this.$refs.editor.$refs.editor.quill.enable(true)
        this.$refs.editor.$refs.editor.quill.blur()
        window.scrollTo(0, 0)
      })
    }
  },

  computed: {
    provinces () {
      return provinces()
    }
  },
  watch: {
    // 标签数组转字符串
    chooseTags () {
      this.form.tags = this.chooseTags?.join(',')
    }
  },
  methods: {
    // 获取页面初始数据
    async getStartData () {
      // 获取学科
      const res = await subjectSimple()
      this.subjects = res.data
      // 获取公司列表
      const res2 = await companesList()
      this.companys = res2.data.items
    },
    // 获取标签与二级目录
    async seachTags (id) {
      this.tags = []
      this.chooseTags = this.$options.data().chooseTags
      this.directorys = []
      this.form.catalogID = null
      this.form.tags = null
      const res = await tagsSimple({ subjectID: id })
      this.tags = res.data
      const res2 = await directorysSimple({ subjectID: id })
      this.directorys = res2.data
    },
    // 获取城市区域
    async seachCitys () {
      this.citys = citys(this.form.province)
    },
    // 添加多选选项
    addOptions () {
      this.form.options.push({
        isRight: 0,
        // 根据编码添加code
        code: String.fromCharCode(this.form.options.length + 65),
        title: '',
        img: ''
      })
    },
    // 上传图片
    uploadPic (file, index) {
      cos.putObject(
        {
          Bucket: 'robot-1318751017', // 存储桶名称
          Region: 'ap-nanjing', // 地域名称
          Key: file.file.name, // 文件名称
          StorageClass: 'STANDARD', // 固定值
          Body: file.file // 文件对象
        },
        (err, data) => {
          if (data.statusCode === 200 && data.Location) {
            // 拿到了腾讯云返回的地址
            // 通过input自定义事件将地址传出去
            this.$set(
              this.form.options[index],
              'img',
              'http://' + data.Location
            )
          } else {
            this.$message.error(err.message) // 上传失败提示消息
          }
        }
      )
    },
    // 删除图片边框
    delPic (index) {
      if (this.form.options.length <= 3) return
      if (this.form.questionType === 2) this.form.options.splice(index, 1)
      this.form.options.forEach((item, index) => {
        item.code = String.fromCharCode(index + 65)
      })
    },
    // 提交试题
    submitForm (formName) {
      this.$refs[formName].validate(async (valid) => {
        if (valid) {
          if (this.loading === false) {
            this.loading = true
            this.form.questionType = this.form.questionType.toString()
            this.form.difficulty = this.form.difficulty.toString()
            if (this.$route.query.id) {
              await updateQuestion(this.form)
              this.$message({
                type: 'success',
                message: '修改成功'
              })
              this.loading = false
              this.$refs.form.resetFields()
              this.$router.push('/questions/list')
            } else {
              // 没有添加时间则执行新增
              await addQuestion(this.form)
              this.$message({
                type: 'success',
                message: '添加成功'
              })
              this.loading = false
              this.$refs.form.resetFields()
              this.$router.push('/questions/list')
            }
          }
        }
      })
    },
    // 选项单选框更改
    changeRadio () {
      this.form.options.forEach((item) => {
        if (item.code === this.radioChecked) {
          item.isRight = 1
        } else {
          item.isRight = 0
        }
      })
    },
    // 选项多选框更改
    changeCheckbox () {
      this.form.options.forEach((item) => {
        item.isRight = 0
        this.checkedList.forEach((item2) => {
          if (item.code === item2) {
            item.isRight = 1
          }
        })
      })
    },
    // 更换题型重置选项
    changeQuestionType () {
      this.form.options = this.$options.data().form.options
      this.radioChecked = null
      this.checkedList = []
    }
  }
}
</script>

<style scoped lang='scss'>
.container {
  padding: 20px;
  .main {
    background-color: #fff;
    padding: 20px;
    box-shadow: 2px 2px 2px #ccc;
    border-radius: 5px;
    .header {
      padding: 18px 20px;
      border-bottom: 1px solid #ebeef5;
      -webkit-box-sizing: border-box;
      box-sizing: border-box;
    }
    .form {
      margin-top: 20px;
      img {
        width: 100px;
        height: 60px;
        margin-left: 10px;
      }
      .el-select,
      .el-input,
      .el-textarea {
        width: 400px;
      }
      .area {
        width: 400px;
        display: flex;
        align-items: center;
        .el-select:first-child {
          margin-right: 10px;
        }
      }
      :deep(.ql-editor) {
        height: 200px;
      }
      .radio {
        .form-inner {
          display: flex;
          align-items: center;
          height: 60px;
        }
        .el-radio {
          display: flex;
          align-items: center;
          width: 100%;
          margin-bottom: 20px;
          .upload {
            position: relative;
            :deep(.el-upload) {
              margin-left: 5px;
              line-height: 60px;
              width: 100px;
              height: 60px;
              border: 1px dashed #d9d9d9;
            }
            i {
              height: 18px;
              width: 18px;
              position: absolute;
              right: -9px;
              top: -9px;
            }
          }
        }
      }
      .checkbox {
        .form-inner {
          display: flex;
          align-items: center;
          height: 60px;
        }
        .el-checkbox {
          display: flex;
          align-items: center;
          width: 100%;
          margin-bottom: 20px;
          .upload {
            position: relative;
            :deep(.el-upload) {
              margin-left: 5px;
              line-height: 60px;
              width: 100px;
              height: 60px;
              border: 1px dashed #d9d9d9;
            }
            i {
              height: 18px;
              width: 18px;
              position: absolute;
              right: -9px;
              top: -9px;
            }
          }
        }
      }
    }
  }
}
</style>
